package db;

import java.net.URL;
import java.sql.*;
import java.util.*;


public class DBConnection {
	//constans used to get access to the database
	//SQL Server
	private static final String  driver = "jdbc:sqlserver://balder.ucn.dk:1433";
	private static final String  databaseName = ";databaseName=DM74_6";
	//jdbc:sqlserver://localhost\SQLEXPRESS/Databases/EPS:1357;user=epsingall;password=welkom1;
	//SQL Server
	private static String  userName = ";user=DM74_6";
	private static String password = ";password=MaaGodt";

	private DatabaseMetaData dma;
	private static Connection con;
	// an instance of the class is generated
	private static DBConnection  instance = null;

	// the constructor is private to ensure that only one object of this class is created
	private DBConnection()
	{
		String url = driver + databaseName + userName + password;

		try{
			//load of driver
			//SQL Server
			Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
			System.out.println("class loaded");

		}
		catch(Exception e){
			System.out.println("Can not find the driver");
			System.out.println(e.getMessage());
		}
		try{
			//connection to the database

			con = DriverManager.getConnection(url);
			//set autocommit
			con.setAutoCommit(true);
			dma = con.getMetaData(); // get meta data
			System.out.println("Connection to " + dma.getURL());
			System.out.println("Driver " + dma.getDriverName());
			System.out.println("Database product name " + dma.getDatabaseProductName());
		}//end try
		catch(Exception e){

			System.out.println("Problems with the connection to the database");
			System.out.println(e.getMessage());
			System.out.println(url);
		}//
	}//

	//closeDb: closes the connection to the database

	public static void CloseConnection(){
		try{
			con.close();
			System.out.println("The connection is closed");
		}
		catch (Exception e){
			System.out.println("Error trying to close the database " + e.getMessage());
		}
	} //end closeDB

	//getDBcon: returns the connection to database
	public  Connection getDBcon()
	{
		return con;
	}

	//this method is used to get the instance of the connection
	public static DBConnection getInstance(){
		if(instance == null){
			instance = new DBConnection();
		}
		return instance;
	}
}//end DbConnection


